package com.exam.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class PrintClass {
	public static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

	public static void print(Object object) {
		StringBuffer str = new StringBuffer();
		str.append("Attribute of instance: " + object.toString() + "\n");
		Field[] fields = object.getClass().getDeclaredFields();
		for (Field field : fields) {
			if (field.getName().equals("serialVersionUID")
					|| field.getName().equals("$VALUES"))
				return;
			String name = getAttrName(field);
			String type = getAttrType(field);
			String value = getAttrValue(object, field, name);
			str.append("Name:" + name);
			str.append("\t\tType:" + type);
			str.append("\t\tValue:" + value);
			str.append("\n");
		}
		System.out.println(str);
	}

	private static String getAttrName(Field field) {
		return field.getName();
	}

	private static String getAttrType(Field field) {
		return field.getGenericType().toString();
	}

	private static String getAttrValue(Object object, Field field,
			String attrName) {
		try {
			Method method = object.getClass().getMethod(
					"get" + attrName.substring(0, 1).toUpperCase()
							+ attrName.substring(1));
			Class type = method.getReturnType();
			Object value = method.invoke(object);
			if ("java.util.Date".equals(type.toString())) {
				dateFormat = DateFormat.getDateInstance(DateFormat.FULL);
				return dateFormat.format(value);
			} else {
				print(value);
				return value.toString();
			}
		} catch (NoSuchMethodException e) {
			// System.out.println("Error: NoSuchMethod: get" +
			// attrName.substring(0, 1).toUpperCase() + attrName.substring(1));
		} catch (InvocationTargetException e) {
			System.out.println("Error: NoInvocationTarget");
		} catch (IllegalAccessException e) {
			System.out.println("Error: IllegalAccess");
		}
		return "";
	}
	/*
	 * public static void main(String[] args) throws ParseException { Date
	 * birthday = dateFormat.parse("1987-08-08"); User user = new
	 * User("baitao.jibt", "badsiu129hqw98ed", User.Gender.MALE, 24, birthday,
	 * new User.Address("china", "shandong", "jinan")); PrintClass.print(user);
	 * }} }
	 */
}
